package com.beverages.messages.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.beverages.messages.client.CustomerIndividualClient;
import com.beverages.messages.common.Result;
import com.beverages.messages.entity.RefundRequest;
import com.beverages.messages.entity.dto.RefundRequestDTO;
import com.beverages.messages.mapper.RefundRequestMapper;
import com.beverages.messages.service.IRefundRequestService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/customer/messages/request-for-refund")
public class RefundRequestController {

    private final RestTemplate restTemplate;
    private static final String TYPESCRIPT_URL = "http://127.0.0.1:9091/send-message/"; //后续需要修改

    @Autowired
    public RefundRequestController(@Qualifier("restTemplateForTypeScript") RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Autowired
    private CustomerIndividualClient customerIndividualClient;

    @Resource
    private IRefundRequestService refundRequestService;

    @Resource
    private RefundRequestMapper refundRequestMapper;

    @ApiOperation(
            value = "获取单个退款申请的未封装数据",
            response = Result.class,
            tags = {"这些接口不用管"}
    )
    @GetMapping("/id/{requestId}")
    public Result<RefundRequest> getRefundRequestById(@PathVariable("requestId") Integer requestId) {
        return Result.success(refundRequestService.getById(requestId));
    }

    @ApiOperation(
            value = "获取单个退款申请的已封装数据",
            notes = "必须传参：\n" +
                    "requestId   (Integer)\n",
            response = Result.class,
            tags = {"获取单个退款申请"}
    )
    @GetMapping("/{requestId}")
    public Result<RefundRequestDTO> getSingleRefundRequestDTOById(@PathVariable("requestId") Integer requestId){
        return Result.success(refundRequestService.convertRefundRequestEntityToRefundRequestDTO(refundRequestService.getById(requestId)));
    }

    @ApiOperation(
            value = "分页查看退款申请",
            notes = "必须传参：\n" +
                    "1: fromCustomerId   (Integer)\n" +
                    "2: pageNum   (Integer)\n" +
                    "3: pageSize   (Integer)\n" +
                    "可选传参：\n" +
                    "1: orderNumber   (String) -- 默认值：\"\" ，即查询该顾客所有退款申请\n" +
                    "2: whetherToBeReplied   (Boolean) ，如果为true，返回已被回复的申请；如果为false，返回未被回复的申请；如果不设置该参数，返回所有申请。是否被回复根据replyId判断，如果replyId=0，就是未被回复。",
            response = Result.class,
            tags = {"查看退款申请"}
    )
    @GetMapping("/page")
    public Result<IPage<RefundRequestDTO>> findRefundRequestPage(@RequestParam Integer pageNum,
                                             @RequestParam Integer pageSize,
                                             @RequestParam Integer fromCustomerId,
                                             @RequestParam(defaultValue = "") String orderNumber,
                                             @RequestParam(required = false) Boolean whetherToBeReplied) {
        IPage<RefundRequest> page = new Page<>(pageNum, pageSize);
        QueryWrapper<RefundRequest> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("from_customer_id",fromCustomerId);
        if (orderNumber != null && !orderNumber.trim().equals("")) {
            queryWrapper.eq("order_number", orderNumber.trim());
        }
        if(whetherToBeReplied != null){
            if(whetherToBeReplied){
                queryWrapper.ne("reply_id",0);
            }else {
                queryWrapper.eq("reply_id",0);
            }
//            queryWrapper = whetherToBeReplied ? queryWrapper.ne("reply_id",0) : queryWrapper.eq("reply_id",0);
        }

        IPage<RefundRequest> resultPage = refundRequestService.page(page, queryWrapper);

        List<RefundRequestDTO> dtoList = resultPage.getRecords().stream().map(refundRequest -> {
            return refundRequestService.convertRefundRequestEntityToRefundRequestDTO(refundRequest);
        }).collect(Collectors.toList());

        IPage<RefundRequestDTO> dtoPage = new Page<>(pageNum, pageSize, resultPage.getTotal());
        dtoPage.setRecords(dtoList);

        return Result.success(dtoPage);
    }

    @ApiOperation(
            value = "分页查看所有退款申请",
            response = Result.class,
            tags = {"这些接口不用管"}
    )
    @GetMapping("/page/show-request-for-merchant")
    public Result<IPage<RefundRequestDTO>> pageShowCustomerRefundRequest(
            @RequestParam(name = "pageNum") Integer pageNum,
            @RequestParam(name = "pageSize") Integer pageSize,
            @RequestParam(name = "orderNumber", defaultValue = "") String orderNumber,
            @RequestParam(name = "whetherOnlyShowUnreplied", defaultValue = "true") Boolean whetherOnlyShowUnreplied) {

        IPage<RefundRequest> page = new Page<>(pageNum, pageSize);
        QueryWrapper<RefundRequest> queryWrapper = new QueryWrapper<>();

        if (orderNumber != null && !orderNumber.trim().equals("")) {
            queryWrapper.eq("order_number", orderNumber.trim());
        }
        if(whetherOnlyShowUnreplied){    //默认查询未被回复的申请
            queryWrapper.eq("reply_id",0);
        }

        IPage<RefundRequest> resultPage = refundRequestService.page(page, queryWrapper);

        List<RefundRequestDTO> dtoList = resultPage.getRecords().stream().map(refundRequest -> {
            return refundRequestService.convertRefundRequestEntityToRefundRequestDTO(refundRequest);
        }).collect(Collectors.toList());

        IPage<RefundRequestDTO> dtoPage = new Page<>(pageNum, pageSize, resultPage.getTotal());
        dtoPage.setRecords(dtoList);

        return Result.success(dtoPage);
    }

    @ApiOperation(
            value = "收到商家回复",
            response = Result.class,
            tags = {"这些接口不用管"}
    )
    @GetMapping("/be-replied")
    public Result refundRequestIsReplied(@RequestParam(name = "requestId") Integer requestId,
                                   @RequestParam(name = "replyId") Integer replyId){
        RefundRequest refundRequest = refundRequestService.getById(requestId);
        refundRequest.setReplyId(replyId);
        refundRequestService.saveOrUpdate(refundRequest);
        return Result.success();
    }

    @ApiOperation(
            value = "发出退款申请",
            notes = "只需传值：\n" +
                    "1: fromCustomerId   (Integer)  ——申请顾客的id\n" +
                    "2: content   (String)  ——申请理由\n" +
                    "3: orderNumber   (String)  ——订单编号\n" +
                    "4: imageId   (Integer)  ——图片id\n\n",
            response = Result.class,
            tags = {"发出退款申请"}
    )
    @PostMapping
    public Result request(@RequestBody RefundRequest refundRequest) {
        refundRequest.setId(null);
        refundRequest.setRequestTime(new Date());
        refundRequest.setReplyId(0);
        refundRequestMapper.insert(refundRequest);
        return Result.success();
    }

}
